<template>
  <!-- 状态1：等待：pending -->
  <div v-if="status">加载中...</div>
  <!-- 状态2：成功fulfilled -->
  <div class="consult-pay-page" v-if="status === 'fulfilled'">
    <van-nav-bar fixed title="支付" left-arrow @click-left="$router.back()" />
    <div class="pay-info">
      <p class="tit">图文问诊 49 元</p>
      <img class="img" src="@/assets/avatar-doctor.svg" />
      <p class="desc">
        <span>极速问诊</span>
        <span>自动分配医生</span>
      </p>
    </div>
    <van-cell-group>
      <van-cell title="优惠券" :value="`-¥${payInfo?.couponDeduction}`" />
      <van-cell title="积分抵扣" :value="`-¥${payInfo?.pointDeduction}`" />
      <van-cell
        title="实付款"
        :value="`¥${payInfo?.actualPayment}`"
        class="pay-price"
      />
    </van-cell-group>
    <div class="pay-space"></div>
    <van-cell-group>
      <van-cell
        title="患者信息"
        :value="` ${patientInfo?.name} | ${patientInfo?.genderValue} | ${patientInfo?.age}岁`"
      ></van-cell>

      <van-cell title="病情描述" label="头痛，头晕，恶心"></van-cell>
    </van-cell-group>
    <div class="pay-schema">
      <van-checkbox v-model="isAgree"
        >我已同意 <span class="text">支付协议</span></van-checkbox
      >
    </div>
    <van-submit-bar
      button-type="primary"
      :price="payInfo?.actualPayment! * 100"
      button-text="立即支付"
      text-align="left"
      @click="openPay"
    />
  </div>
  <!-- 状态3：失败：rejected -->
  <div v-if="status === 'rejected'">加载失败,请重试</div>

  <van-action-sheet
    v-model:show="isShow"
    title="选择支付方式"
    :close-on-popstate="false"
    :closeable="false"
    :before-close="onClose"
  >
    <div class="pay-type">
      <p class="amount">￥20.00</p>
      <van-cell-group>
        <van-cell
          title="微信支付"
          @click="paymentMethod = PayMethodEnum.WeChat"
        >
          <template #icon><cp-icon name="consult-wechat" /></template>
          <template #extra
            ><van-checkbox :checked="paymentMethod === PayMethodEnum.WeChat"
          /></template>
        </van-cell>
        <van-cell
          title="支付宝支付"
          @click="paymentMethod = PayMethodEnum.AliPay"
        >
          <template #icon><cp-icon name="consult-alipay" /></template>
          <template #extra
            ><van-checkbox :checked="paymentMethod === PayMethodEnum.AliPay"
          /></template>
        </van-cell>
      </van-cell-group>
      <div class="btn">
        <van-button type="primary" round block @click="pay"
          >立即支付</van-button
        >
      </div>
    </div>
  </van-action-sheet>
</template>

<script setup lang="ts">
import { createOrder, getOrderPre, payMethod } from '@/api/consult'
import { getPatientDetail } from '@/api/user'
import { useConsultStore } from '@/stores'
import type { ConsultOrderPreData } from '@/types/consult'
import type { Patient } from '@/types/user'
import { showConfirmDialog, showFailToast } from 'vant'
import { ref } from 'vue'
import { PayMethodEnum } from '@/enums'
import { onBeforeRouteLeave } from 'vue-router'
import router from '@/router'

// 1. 获取患者信息
const store = useConsultStore()
const patientInfo = ref<Patient>()
const status = ref('')
const getPatientInfo = async () => {
  try {
    const { data } = await getPatientDetail(store.consult.patientId!)
    patientInfo.value = data
  } catch (error) {
    console.log(error)
  }
}

// 2.获取支付相关的信息
const payInfo = ref<ConsultOrderPreData>()
const getPayInfo = async () => {
  const { data } = await getOrderPre({
    type: store.consult.type,
    illnessType: store.consult.illnessType!
  })
  payInfo.value = data
  // 存储优惠卷id
  store.setCouponId(data.couponId)
}

const getPageInfo = async () => {
  status.value = 'pending'
  try {
    await new Promise((resove, reject) => {
      let count = 0
      getPatientInfo().then(isAllSuccess).catch(reject)
      getPayInfo().then(isAllSuccess).catch(reject)

      function isAllSuccess() {
        if (count === 1) resove(count)
      }
      count++
    })
    status.value = 'fulfilled'
  } catch (error) {
    status.value = 'rejected'
  }
}
getPageInfo()

// 创建支付
const isAgree = ref(true) // 是否同意协议
const isShow = ref(false) // 支付抽屉的显示与隐藏
const orderId = ref() // 问诊订单id
const openPay = async () => {
  if (!isAgree.value) return showFailToast('请勾选协议')
  // 1. 创建订单
  const { data } = await createOrder(store.consult)
  orderId.value = data.id
  // 2. 打开支付方式弹窗
  isShow.value = true
}

// 发起支付
const paymentMethod = ref()
// 调起支付宝支付
const pay = async () => {
  const res = await payMethod({
    paymentMethod: paymentMethod.value,
    orderId: orderId.value,
    payCallback: 'http://127.0.0.1:5173/room'
  })
  window.location.href = res.data.payUrl
}

onBeforeRouteLeave(() => {
  // 生成订单id的情况下，没支付拒绝离开页面
  if (orderId.value) return false
})

const onClose = async () => {
  const res = await showConfirmDialog({
    title: '关闭支付',
    message: '取消支付将无法获得医生回复，医生接诊名额有限，是否确认关闭？',
    cancelButtonText: '仍要关闭',
    confirmButtonText: '继续支付'
  }).catch((err) => err)

  // 确认关闭：跳转到 用户问诊记录列表页面
  if (res === 'cancel') {
    // 清空orderId 绕过onBeforeRouteLeave的判断逻辑
    orderId.value = ''
    router.push('/user/consult')
    return true // 关闭支付弹窗
  }
  return false // 不关闭支付弹窗
}
</script>

<style lang="scss" scoped>
.consult-pay-page {
  padding: 46px 0 50px 0;
}
.pay-info {
  display: flex;
  padding: 15px;
  flex-wrap: wrap;
  align-items: center;
  .tit {
    width: 100%;
    font-size: 16px;
    margin-bottom: 10px;
  }
  .img {
    margin-right: 10px;
    width: 38px;
    height: 38px;
    border-radius: 4px;
    overflow: hidden;
  }
  .desc {
    flex: 1;
    > span {
      display: block;
      color: var(--cp-tag);
      &:first-child {
        font-size: 16px;
        color: var(--cp-text2);
      }
    }
  }
}
.pay-price {
  ::v-deep() {
    .vam-cell__title {
      font-size: 16px;
    }
    .van-cell__value {
      font-size: 16px;
      color: var(--cp-price);
    }
  }
}
.pay-space {
  height: 12px;
  background-color: var(--cp-bg);
}
.pay-schema {
  height: 56px;
  display: flex;
  align-items: center;
  justify-content: center;
  .text {
    color: var(--cp-primary);
  }
}
::v-deep() {
  .van-submit-bar__button {
    font-weight: normal;
    width: 160px;
  }
}
.pay-type {
  .amount {
    padding: 20px;
    text-align: center;
    font-size: 16px;
    font-weight: bold;
  }
  .btn {
    padding: 15px;
  }
  .van-cell {
    align-items: center;
    .cp-icon {
      margin-right: 10px;
      font-size: 18px;
    }
    .van-checkbox :deep(.van-checkbox__icon) {
      font-size: 16px;
    }
  }
}
</style>
